package com.example.wm.controller;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wm.common.Result;
import com.example.wm.common.ResultData;
import com.example.wm.entity.*;

import com.example.wm.service.*;
import com.example.wm.utils.TsyUtils;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/ProductLibrary")
public class ProductLibraryContoller {
    @Resource
    private ProductLibraryService productLibraryService;
    @Resource
    private ProductorMaterialTypeService productorMaterialTypeService;
    @Resource
    private ProductTypeNumService productTypeNumService;

    @Resource
    private TsyUtils tsyUtils;
    @Resource
    private MaterialLibraryService materialLibraryService;
@Value("${Coze.accessToken}")
private  String accessToken;
    @Transactional
    @PostMapping("/save")
    // 产品
    public Result save(@RequestBody ProductLibrary productLibrary) {
        productLibrary.setInserttime(tsyUtils.getnowtime());
        Boolean b = productLibraryService.save(productLibrary);
        return ResultData.success(b);
    }

    @Transactional
    @PostMapping("/saveBatch")
    public Result saveBatch(@RequestBody List<ProductLibrary> productLibrarys) {
        for (ProductLibrary p : productLibrarys) {
            p.setInserttime(tsyUtils.getnowtime());
        }
        Boolean b = productLibraryService.saveBatch(productLibrarys);
        return ResultData.success(b);
    }

    @PostMapping("/update")
    public Result update(@RequestBody ProductLibrary productLibrary) {
        productLibrary.setUpdatetime(tsyUtils.getnowtime());
        Boolean b = productLibraryService.updateById(productLibrary);
        return ResultData.success(b);
    }

    // 材料
    @Transactional
    @PostMapping("/updatemateria")
    public Result updatemateria(@RequestBody MaterialLibrary materialLibrary) {
        materialLibrary.setUpdatetime(tsyUtils.getnowtime());
        Boolean b = materialLibraryService.updateById(materialLibrary);
        return ResultData.success(b);
    }

    @Transactional
    @PostMapping("/savemateria")
    public Result savemateria(@RequestBody MaterialLibrary materialLibrary) {
        materialLibrary.setInserttime(tsyUtils.getnowtime());
        Boolean b = materialLibraryService.save(materialLibrary);
        return ResultData.success(b);
    }
    // 查询产品名

    @PostMapping("/findpro")
    public Result findpro(@RequestBody ProductLibrary productLibrary) {
        LambdaQueryWrapper<ProductLibrary> lq = new LambdaQueryWrapper<>();
        if (!Objects.equals(productLibrary.getProname(), "")) {
            lq.like(ProductLibrary::getProname, productLibrary.getProname());


        }
        List<ProductLibrary> list = productLibraryService.list(lq);
        return ResultData.success(list);
    }

    // 查询材料
    @PostMapping("/findmeter")
    public Result findmeter(@RequestBody MaterialLibrary materialLibrary) {
        LambdaQueryWrapper<MaterialLibrary> lq = new LambdaQueryWrapper<>();
        if (!Objects.equals(materialLibrary.getMatername(), "")) {
            lq.like(MaterialLibrary::getMatername, materialLibrary.getMatername());
        }
        List<MaterialLibrary> list = materialLibraryService.list(lq);
        return ResultData.success(list);
    }

    // 类名
    @Transactional
    @PostMapping("/saveType")
    public Result saveType(@RequestBody ProductorMaterialType productorMaterialType) {
        Boolean b = productorMaterialTypeService.save(productorMaterialType);
        return ResultData.success(b);
    }

    // 型号
    @Transactional
    @PostMapping("/saveTypeNum")
    public Result saveTypeNum(@RequestBody ProductTypeNum productTypeNum) {
        Boolean b = productTypeNumService.save(productTypeNum);
        return ResultData.success(b);
    }

    // 查询类名
    @Transactional
    @PostMapping("/findtype")
    public Result findtype(@RequestBody ProductorMaterialType productorMaterialType) {
        LambdaQueryWrapper<ProductorMaterialType> lq = new LambdaQueryWrapper<>();
        lq.eq(ProductorMaterialType::getType, productorMaterialType.getType());
        List<ProductorMaterialType> list = productorMaterialTypeService.list(lq);
        return ResultData.success(list);
    }

    // 查询型号
    @Transactional
    @PostMapping("/findtypenum")
    public Result findtypenum() {

        List<ProductTypeNum> list = productTypeNumService.list();
        return ResultData.success(list);
    }

    // 查找图片
    @PostMapping("/findproductimg")
    public Result findproductimg(@RequestBody ProductLibrary productLibrary) {
        LambdaQueryWrapper<ProductLibrary> lq = new LambdaQueryWrapper<>();
        lq.eq(ProductLibrary::getId, productLibrary.getId());
        ProductLibrary productLibrary1 = productLibraryService.getOne(lq);
        return ResultData.success(productLibrary1);
    }

    // 获取产品

    @Transactional
    @PostMapping("/pageProductLibrary")
    public Result pageProductLibrary(@RequestBody JSONObject jsonObject) {
        LambdaQueryWrapper<ProductLibrary> lq = new LambdaQueryWrapper<>();
        Page<ProductLibrary> pageInfo = new Page<>(jsonObject.getLong("page"), jsonObject.getLong("pageSize"));
        Page<ProductLibrary> list = productLibraryService.page(pageInfo, lq);

        return ResultData.success(list);
    }

    @Transactional
    @PostMapping("/ProductLibrary")
    public Result ProductLibrary() {
        LambdaQueryWrapper<ProductLibrary> lq = new LambdaQueryWrapper<>();
        // Page<ProductLibrary> pageInfo = new
        // Page<>(jsonObject.getLong("page"),jsonObject.getLong("pageSize"));
        List<ProductLibrary> list = productLibraryService.list(lq);

        return ResultData.success(list);
    }

    @Transactional
    @PostMapping("/pageMaterial")
    public Result pageMaterial(@RequestBody JSONObject jsonObject) {
        LambdaQueryWrapper<MaterialLibrary> lq = new LambdaQueryWrapper<>();
        lq.eq(MaterialLibrary::getType,jsonObject.getString("type"));
        Page<MaterialLibrary> pageInfo = new Page<>(jsonObject.getLong("page"), jsonObject.getLong("pageSize"));
        Page<MaterialLibrary> list = materialLibraryService.page(pageInfo, lq);

        return ResultData.success(list);
    }

    @PostMapping("/getMaterial")
    public Result getMaterial() {
        LambdaQueryWrapper<MaterialLibrary> lq = new LambdaQueryWrapper<>();
        List<MaterialLibrary> list = materialLibraryService.list(lq);
        return ResultData.success(list);
    }

    // 搜索材料
    @PostMapping("/findmaterial")
    public Result findmaterial(@RequestBody MaterialLibrary materialLibrary) {
        LambdaQueryWrapper<MaterialLibrary> lq = new LambdaQueryWrapper<>();
        lq.eq(MaterialLibrary::getType,materialLibrary.getType());

        if (!Objects.equals(materialLibrary.getMatername(), "")) {
            lq.like(MaterialLibrary::getMatername, materialLibrary.getMatername());

        }
        List<MaterialLibrary> list = materialLibraryService.list(lq);
        return ResultData.success(list);
    }

    // 搜索产品名称,型号,品牌
    @PostMapping("/findproduct")
    public Result findproduct(@RequestBody ProductLibrary productLibrary) {
        ArrayList<ProductLibrary> arrayList = new ArrayList<>();
        if (!Objects.equals(productLibrary.getProname(), "")
                && !Objects.equals(productLibrary.getTypenum(), "")
                && !Objects.equals(productLibrary.getTypename(), "")



        ) {
            LambdaQueryWrapper<ProductLibrary> lq = new LambdaQueryWrapper<>();
            lq.like(ProductLibrary::getProname, productLibrary.getProname());
            List<ProductLibrary> list = productLibraryService.list(lq);
            arrayList.addAll(list);
            LambdaQueryWrapper<ProductLibrary> lq2 = new LambdaQueryWrapper<>();
            lq2.like(ProductLibrary::getTypenum, productLibrary.getTypenum());
            List<ProductLibrary> list2 = productLibraryService.list(lq2);
            arrayList.addAll(list2);
//            LambdaQueryWrapper<ProductLibrary> lq3 = new LambdaQueryWrapper<>();
//            lq3.like(ProductLibrary::getTypename, productLibrary.getTypename());
//            List<ProductLibrary> list3 = productLibraryService.list(lq3);
//            arrayList.addAll(list3);
            LambdaQueryWrapper<ProductLibrary> lq4= new LambdaQueryWrapper<>();
            lq4.like(ProductLibrary::getProname, productLibrary.getProname());
            List<ProductLibrary> list4 = productLibraryService.list(lq4);
            arrayList.addAll(list4);

        } else {
            LambdaQueryWrapper<ProductLibrary> lq = new LambdaQueryWrapper<>();
            List<ProductLibrary> list = productLibraryService.list(lq);
            arrayList.addAll(list);

        }

        return ResultData.success(arrayList);
    }

    // 根据型号搜索产品
    @PostMapping("/findproductbytype")
    public Result findproductbytype(@RequestBody ProductLibrary productLibrary) {
        LambdaQueryWrapper<ProductLibrary> lq = new LambdaQueryWrapper<>();
        if (!Objects.equals(productLibrary.getTypename(), "全部")) {
            lq.eq(ProductLibrary::getTypename, productLibrary.getTypename());

        }
        List<ProductLibrary> list = productLibraryService.list(lq);
        return ResultData.success(list);
    }
       //模糊查询材料
       @PostMapping("/findmateria")
       public Result findmateria(@RequestBody MaterialLibrary materialLibrary) {
           LambdaQueryWrapper<MaterialLibrary> lq = new LambdaQueryWrapper<>();
           lq.like(MaterialLibrary::getMatername, materialLibrary.getMatername());
           List<MaterialLibrary> list = materialLibraryService.list(lq);
           return ResultData.success(list);
       }

    // 自动报价
    @PostMapping("/chatAi")
    public Result chatAi(@RequestBody JSONObject jsonObject) {
        try {
            String baseUrl = "https://api.coze.cn/v1/workflow/run";

            Map<String, Object> parameters = new HashMap<>();
            parameters.put("input", jsonObject.getString("input"));

            Map<String, Object> requestParam = new HashMap<>();
            requestParam.put("workflow_id", "7498634805967732773");
            requestParam.put("parameters", parameters);

            String jsonStr = JSONUtil.toJsonStr(requestParam);

            // 添加调试日志
            System.out.println("请求URL: " + baseUrl);
            System.out.println("请求参数: " + jsonStr);

            HttpResponse response = HttpRequest.post(baseUrl)
                    .header(Header.CONTENT_ENCODING, "UTF-8")
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.AUTHORIZATION,
                            accessToken) // 更新 Token
                    .body(jsonStr)
                    .execute();

            // 添加响应调试
            System.out.println("响应状态码: " + response.getStatus());
            System.out.println("响应内容: " + response.body());

            if (response.getStatus() == HttpStatus.HTTP_OK) {
                String result = response.body();
                ObjectMapper mapper = new ObjectMapper();
                Map<String, Object> responseMap = mapper.readValue(result, Map.class);
                return ResultData.success(responseMap);
            } else {
                return ResultData.error(500, "API调用失败,状态码: " + response.getStatus() + ", 响应: " + response.body());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.error(500, "请求异常: " + e.getMessage());
        }
    }
    // 预估投标价
    @PostMapping("/chatestimatic")
    public Result chatestimatic(@RequestBody JSONObject jsonObject) {
        try {
            String baseUrl = "https://api.coze.cn/v1/workflow/run";

            Map<String, Object> parameters = new HashMap<>();
            parameters.put("file_id", jsonObject.getString("file_id"));
            Map<String, Object> parameters2 = new HashMap<>();
            parameters2.put("input", parameters);


            Map<String, Object> requestParam = new HashMap<>();
            requestParam.put("workflow_id", "7530931064400740362");
            requestParam.put("parameters", parameters2);

            String jsonStr = JSONUtil.toJsonStr(requestParam);

            // 添加调试日志
            System.out.println("请求URL: " + baseUrl);
            System.out.println("请求参数: " + jsonStr);

            HttpResponse response = HttpRequest.post(baseUrl)
                    .header(Header.CONTENT_ENCODING, "UTF-8")
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.AUTHORIZATION,
                             accessToken) // 更新 Token
                    .body(jsonStr)
                    .execute();

            // 添加响应调试
            System.out.println("响应状态码: " + response.getStatus());
            System.out.println("响应内容: " + response.body());

            if (response.getStatus() == HttpStatus.HTTP_OK) {
                String result = response.body();
                ObjectMapper mapper = new ObjectMapper();
                Map<String, Object> responseMap = mapper.readValue(result, Map.class);
                return ResultData.success(responseMap);
            } else {
                return ResultData.error(500, "API调用失败,状态码: " + response.getStatus() + ", 响应: " + response.body());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.error(500, "请求异常: " + e.getMessage());
        }
    }

//    @PostMapping("/savetagBatch")
//    public Result savetagBatch(@RequestBody List<ProductTypeNum> productTypeNums) {
//
//        Boolean a = productTypeNumService.saveBatch(productTypeNums);
//        return ResultData.success(a);
//    }
//    @PostMapping("/chatAi")
//    public Result chatAi(@RequestBody JSONObject jsonObject) {
//        try {
//            // 尝试正确的端点
//            String baseUrl = "https://api.coze.cn/v1/workflow/run"; // 注意是单数形式
//
//            Map<String, Object> requestParam = new HashMap<>();
//            requestParam.put("workflow_id", "7498634805967732773");
//
//            Map<String, Object> parameters = new HashMap<>();
//            parameters.put("input", jsonObject.getString("input"));
//            requestParam.put("parameters", parameters);
//
//            String jsonStr = JSONUtil.toJsonStr(requestParam);
//
//            System.out.println("请求URL: " + baseUrl);
//            System.out.println("请求参数: " + jsonStr);
//
//            HttpResponse response = HttpRequest.post(baseUrl)
//                    .header(Header.CONTENT_ENCODING, "UTF-8")
//                    .header(Header.CONTENT_TYPE, "application/json")
//                    .header(Header.AUTHORIZATION, "Bearer pat_IQYea7H2XldhYdpfPWtHJUHO6eZBetzpSSFKwI2rjXXBXlIDOx7fyyEMndGHS9TF")
//                    .body(jsonStr)
//                    .execute();
//
//            System.out.println("响应状态码: " + response.getStatus());
//            System.out.println("响应内容: " + response.body());
//
//
//            if (response.getStatus() == HttpStatus.HTTP_OK) {
//                String result = response.body();
//                ObjectMapper mapper = new ObjectMapper();
//                Map<String, Object> responseMap = mapper.readValue(result, Map.class);
//
//                // 解析嵌套的响应结构
//
//                    if (responseMap.containsKey("data")) {
//                        String dataString = (String) responseMap.get("data");
//
//                        // 解析 data 字段中的 JSON 字符串
//                        Map<String, Object> innerData = mapper.readValue(dataString, Map.class);
//                        if (innerData.containsKey("output")) {
//                            String output = (String) innerData.get("output");
//                            return ResultData.success(output); // 只返回 output 内容
//                        }
//                    }
//
//
//                // 如果解析失败,返回原始响应
//                return ResultData.success(responseMap);
//            } else {
//                return ResultData.error(500, "API调用失败,状态码: " + response.getStatus() + ", 响应: " + response.body());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResultData.error(500, "请求异常: " + e.getMessage());
//        }
//    }

}
